﻿using FPSO.HMI.Utils;
using FPSO.Models.Constant;
using FPSO.Models.Domain;
using FPSO.Services;
using FPSO.Services.Impl;
using FPSO.ViewModel.Controls;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace FPSO.HMI.Views.Dialog
{
    /// <summary>
    /// LoginDialog.xaml 的交互逻辑
    /// </summary>
    public partial class LoginDialog : Window
    {


        public LoginDialog()
        {
            InitializeComponent();
            // 便于测试，默认填写普通用户
            UsernameTextBox.Text = "admin";
            PasswordTextBox.Password = "123456";
        }

        /// <summary>
        /// 登录逻辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LoginButton_Click(object sender, RoutedEventArgs e)
        {
            // 获取用户输入的用户名和密码
            string username = UsernameTextBox.Text;
            string password = PasswordTextBox.Password;
            // 基本格式校验
            if (string.IsNullOrWhiteSpace(username))
            {
                MessageBox.Show("用户名不能为空！", "校验失败");
                return;
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("密码不能为空！", "校验失败");
                return;
            }
            if (password.Length < 6)
            {
                MessageBox.Show("密码长度不小于6位！", "校验失败");
                return;
            }
            // 获取App.config文件中的数据库连接配置
            string ConnectionString = ConfigurationManager.AppSettings["MySQLStr"];
            // 实例化数据库连接
            using (MySqlConnection connection = new MySqlConnection(ConnectionString))
            {
                try
                {
                    connection.Open();
                    // 校验用户名密码，同时返回用户类型，0：普通用户，1：管理员用户
                    string query = "SELECT type FROM sys_user WHERE username = @username AND password = @password";
                    MySqlCommand cmd = new MySqlCommand(query, connection);
                    cmd.Parameters.AddWithValue("@username", username);
                    cmd.Parameters.AddWithValue("@password", password);

                    object userType = cmd.ExecuteScalar();

                    if (userType != null)
                    {
                        int userTypeValue = Convert.ToInt32(userType);
                        // 判断是否为登录成功值
                        if (userTypeValue == 0 || userTypeValue == 1)
                        {
                            // 返回dialog结果为true
                            this.DialogResult = true;
                            // 将用户登录情况缓存至全局变量
                            AuthUtil.SetLoginStatus(userTypeValue);
                            AuthUtil.SetLoginUser(username);
                        }
                        else
                        {
                            MessageBox.Show("登陆异常，请重试！", "登录失败");
                        }

                    }
                    else
                    {
                        AlarmUtil.AddAlarmInfo("用户【" + username + "】尝试登录失败");
                        MessageBox.Show("用户名或密码错误！", "登录失败");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生异常: {ex.Message}", "登录失败");
                }
            }

        }

        /// <summary>
        /// 退出事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitButton_Click(object sender, RoutedEventArgs e)
        {
            //返回false以阻止后续流程并退出 
            this.DialogResult = false;
        }

        /// <summary>
        /// 密码输入框绑定回车键事件，触发登录操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PasswordTextBox_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                LoginButton_Click(sender, e);
            }
        }


        /// <summary>
        /// 窗口拖动事件
        /// </summary>
        private void Grid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DragMove();
            }
        }


    }
}
